package sgd.tp2.server.net.tcp;

import java.io.IOException;
import java.io.ObjectInputStream;

import sgd.tp2.api.cdr.CDR;
import sgd.tp2.api.logging.Log;
import sgd.tp2.api.net.CDRFormatType;
import sgd.tp2.api.net.CEPType;

public class TCPServerObject extends TCPServer {

	public TCPServerObject(CDRFormatType cdrFormatType, int port, CEPType cepType) {
		super(cdrFormatType, port, cepType);
	}

	@Override
	public void run() {
		ObjectInputStream inStream = null;
		Object receivedObj = null;

		try {
			inStream = new ObjectInputStream(socket.getInputStream());

			while ((receivedObj = inStream.readObject()) != null) {
				receivedCDR();
				
				handleObject(receivedObj);
			}

		} catch (IOException e) {
			Log.infoln("");
			Log.warningln("Parou de receber. Servidor terminado");
			stopServer();
			return;
		} catch (ClassNotFoundException e) {
			Log.warningln("Impossivel transformar Object mensagem em CDR.");
		}

	}

	public void handleObject(Object object) {
		startCDRHandling();
		
		CDR cdr = (CDR) object;
		handleCDR(cdr);
		
		endCDRHandling(cdr);
	}
}
